package com.yj.provider.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Time {
    public static void main(String[] args) throws ParseException {
       timestamp2Date("1623335458","yyyy-MM-dd HH:mm:ss");

        boolean b = isLatestWeek(1624947658);
        System.out.println(b);

        String now = "2021-06-29 14:20:58";
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(dateFormat.parse(now).getTime());

    }

    /*
     * 将10 or 13 位时间戳转为时间字符串
     * convert the number 1407449951 1407499055617 to date/time format timestamp
     */
    public static String timestamp2Date(String str_num,String format ) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        if (str_num.length() == 13) {
            String date = sdf.format(new Date(Long.parseLong(str_num)));
            System.out.println("timestamp2Date"+ "将13位时间戳:" + str_num + "转化为字符串:"+ date);
            return date;
        } else {
            String date = sdf.format(new Date(Integer.parseInt(str_num) * 1000L));
            System.out.println("timestamp2Date" + "将10位时间戳:" + str_num + "转化为字符串:"+ date);
            return date;
        }
    }



    //判断最近登录时间是否是7天内
    public static boolean isLatestWeek(Integer lastLoginTime){

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String format = dateFormat.format(new Date(lastLoginTime * 1000l));
        Date time = null;
        try {
            time = dateFormat.parse(format);
            Date now = new Date();
            Calendar calendar = Calendar.getInstance();  //得到日历
            calendar.setTime(now);//把当前时间赋给日历
            calendar.add(Calendar.DAY_OF_MONTH, -7);  //设置为7天前
            Date before7days = calendar.getTime();   //得到7天前的时间
            if(before7days.getTime() < time.getTime()){
                return true;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return false;
    }
}
